﻿using System;
using System.Text;
using System.IO;
using System.Reflection;
using SeizyUtils.Common.Utilities;
using SeizyUtils.AppCode.Common.Data.Csv;

namespace SeizyUtils.Common.Data.Csv
{
    class CsvWriterForBean : ICsvWriter<IBean>
    {

        private readonly HandyFile _file;

        private StreamWriter _writer;

        private bool _isFirst = true;

        public CsvWriterForBean(HandyFile file)
        {
            _file = file;
            _writer = new StreamWriter(_file.getFileStream(FileMode.Create), Encoding.GetEncoding("Shift-JIS"));
        }

        public void writeLine(IBean record)
        {
            string result;
            if (_isFirst)
            {
                _isFirst = false;
                result = createColumnLine(record);
                _writer.WriteLine(result);
            }

            result = createLine(record);
            _writer.WriteLine(result);
        }


        public void close()
        {
            _writer.Close();
        }

        private static string createColumnLine(IBean record)
        {
            StringBuilder builder = new StringBuilder();
            Type type = record.GetType();
            foreach (PropertyInfo field in type.GetProperties())
            {
                if (builder.Length > 0)
                {
                    builder.Append(",");
                }
                builder.Append(CsvHelper.escapeQuato(field.Name));
            }
            return builder.ToString();
        }

        private static string createLine(IBean record)
        {
            StringBuilder builder = new StringBuilder();
            Type type = record.GetType();
            foreach (PropertyInfo field in type.GetProperties())
            {
                if (builder.Length > 0)
                {
                    builder.Append(",");
                }
                string v = TypeUtils.castString(field.GetValue(record, null));
                builder.Append(CsvHelper.escapeQuato(v));
            }
            return builder.ToString();
        }


        #region IDisposable メンバ

        public void Dispose()
        {
            // ファイルを閉じる
            close();

        }

        #endregion
    }
}
